home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / program / swagn_r.zip / NUMBERS.SWG / 0001_BITS1.PAS.pas next >
Pascal/Delphi Source File  |  1993-05-28  |  2KB  |  76 lines

  1. {
  2.  Sean Palmer
  3.  
  4. > What if I want to just access a bit?  Say I have a Byte, to store
  5. > Various access levels (if it does/doesn't have this, that, or the
  6. > other).  How can I
  7.  
  8. > 1)  Access, say, bit 4?
  9. > 2)  Give, say, bit 4, a value of 1?
  10.  
  11. > I have a simple routine that does "GetBit:= Value SHR 1;" to return
  12. > a value, but how can I *SET* a value?  And is the above a good
  13. > method? I only have TP5.5, so I can't do the Asm keyWord (yet..).
  14.  
  15. You COULD use TP sets to do it...
  16. }
  17.  
  18. Type
  19.   tByte = set of 0..7;
  20. Var
  21.   b : Byte;
  22.  
  23. {to get:
  24.   Write('Bit 0 is ',Boolean(0 in tByte(b)));
  25.  
  26. to set:
  27.   tByte(b):=tByte(b)+[1,3,4]-[0,2];
  28. }
  29.  
  30. Type
  31.   bitNum = 0..7;
  32.   bit    = 0..1;
  33.  
  34. Function getBit(b : Byte; n : bitNum) : bit;
  35. begin
  36.   getBit := bit(odd(b shr n));
  37. end;
  38.  
  39. Function setBit( b : Byte; n : bitNum) : Byte;
  40. begin
  41.   setBit := b or (1 shl n);
  42. end;
  43.  
  44. Function clrBit(b : Byte; n : bitNum) : Byte;
  45. begin
  46.   clrBit := b and hi($FEFF shl n);
  47. end;
  48.  
  49. {
  50.  OR.....using Inline() code  (the fastest)
  51.  These are untested but I'm getting fairly good at assembling by hand...8)
  52. }
  53.  
  54. Function getBit(b : Byte; n : bitNum) : bit;
  55. Inline(
  56.   $59/      {pop cx}
  57.   $58/      {pop ax}
  58.   $D2/$E8/  {shr al,cl}
  59.   $24/$01); {and al,1}
  60.  
  61. Function setBit(b : Byte; n : bitNum) : Byte;
  62. Inline(
  63.   $59/      {pop cx}
  64.   $58/      {pop ax}
  65.   $B3/$01/  {mov bl,1}
  66.   $D2/$E3/  {shl bl,cl}
  67.   $0A/$C3); {or al,bl}
  68.  
  69. Function clrBit(b : Byte; n : bitNum) : Byte;
  70. Inline(
  71.   $59/      {pop cx}
  72.   $58/      {pop ax}
  73.   $B3/$FE/  {mov bl,$FE}
  74.   $D2/$C3/  {rol bl,cl}
  75.   $22/$C3); {or al,bl}
  76.